package cn.gov.cus.rmftquartz.config;

import com.alibaba.druid.pool.DruidDataSource;//druid-1.1.6.jar
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author wxming.
 * @date 2018/2/9.
 */
@Configuration
@MapperScan(basePackages = SqlServerDataSourceConfig.PACKAGE,sqlSessionFactoryRef = "sqlServerSqlSessionFactory")
public class SqlServerDataSourceConfig {
    static final String PACKAGE ="cn.gov.cus.rmftras.mappers.sqlserver";

    @Value("${datasource.sqlserver.h2000_app.url}")
    private String url;
    @Value("${datasource.sqlserver.h2000_app.user}")
    private String user;
    @Value("${datasource.sqlserver.h2000_app.password}")
    private String password;
    @Value("${datasource.sqlserver.h2000_app.driver-class-name}")
    private String driverClassName;

    @Bean(name = "sqlServerDataSource")
    public DataSource sqlServerDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setValidationQuery("select 1");
        dataSource.setValidationQueryTimeout(30);

        return dataSource;
    }

    @Bean(name = "sqlServerTransactionManager")
    public DataSourceTransactionManager sqlServerTransactionManager(){
        return new DataSourceTransactionManager(sqlServerDataSource());
    }

    @Bean(name = "sqlServerSqlSessionFactory")
    public SqlSessionFactory sqlServerSqlSessionFactory(@Qualifier("sqlServerDataSource") DataSource sqlServerDataSource) throws Exception{
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();

        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setMapUnderscoreToCamelCase(true);
        config.setCallSettersOnNulls(true);
        sessionFactoryBean.setConfiguration(config);

        sessionFactoryBean.setDataSource(sqlServerDataSource);
        return sessionFactoryBean.getObject();
    }

}
